package com.bp.exam;

import com.alibaba.fastjson.JSONObject;
import com.bianmaba.spring.security.basic.handler.AjaxGlobalExceptionHandler;
import com.bianmaba.spring.security.util.ResponseUtil;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
@ConditionalOnClass({AjaxGlobalExceptionHandler.class})
public class HttpGlobalExceptionHandler extends AjaxGlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpGlobalExceptionHandler.class);
    private static String key ="com.bianmaba.quality";

    public HttpGlobalExceptionHandler() {
    }

    @ExceptionHandler({Exception.class, RuntimeException.class})
    public void handleException(HttpServletRequest request, HttpServletResponse response, Exception e) throws IOException {

        Map<String, Object> result = new HashMap<String, Object>(0);
        result.put("code", 500);
        result.put("statusText", e.getLocalizedMessage());
        result.put("SecurityMessage", true);
        result.put("msg", "资源请求失败，请求的资源出现异常！");
        result.put("failureType", e.getClass().getSimpleName());
        result.put("exception", ExceptionUtils.getStackTrace(e));
        result = e(e.getClass().getSimpleName(), e,result);
//        result.put("exception", result.get("outside"));
        ResponseUtil.writeJson(response, result, 500);
        LOGGER.error(result.get("msg").toString(), e);

    }

    public static Map<String, Object> e(String tag, Throwable t,Map<String, Object> result) {
        StringBuffer inside = new StringBuffer();
        String outside = null;
        StackTraceElement[] elements = t.getStackTrace();
        for (int i = 0; i < elements.length; i++) {
            StackTraceElement element = elements[i];
            if (element.toString().contains(key)) {
                if (inside == null) {
                    inside.append("/n").append(element.toString());
                } else {
                    outside = element.toString();
                }
            }
        }
        String exMsg = t.toString() + "---- tinside ---> " + inside + "---- toutside ---> " + outside;
        JSONObject json = new JSONObject();
        json.put("date", LocalDateTime.now().toString());
        json.put("code", "500");
        json.put("message", "异常 : " + exMsg);
        json.put("errorExplain", tag);

        result.put("outside",outside);
        result.put("inside",inside);
        result.put("throwable",t.toString());
        LOGGER.error(json.toString());
        return result;
    }
}
